import Ionicons from "@expo/vector-icons/Ionicons";
import { Audio } from "expo-av";
import * as DocumentPicker from "expo-document-picker";
import * as FileSystem from "expo-file-system";
import * as ImagePicker from "expo-image-picker";
import { useRouter } from "expo-router";
import * as VideoThumbnails from "expo-video-thumbnails";
import React, { useEffect, useRef, useState } from "react";
import {
  Alert,
  Animated,
  Dimensions,
  GestureResponderEvent,
  Image,
  Modal,
  SafeAreaView,
  SectionList,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from "react-native";
import {
  Menu,
  MenuOption,
  MenuOptions,
  MenuProvider,
  MenuTrigger,
} from "react-native-popup-menu";
import logo from "../../assets/images/react-logo.png";
import { DATA_FILE } from "../../constants/Path";
import type { RecordItem, Section } from "../../constants/types";
// 关于本地文件的处理

export async function saveData(item: RecordItem) {
  try {
    const info = await FileSystem.getInfoAsync(DATA_FILE);
    if (info.exists) {
      const content = await FileSystem.readAsStringAsync(DATA_FILE);
      const list = JSON.parse(content);
      const existingIndex = list.findIndex((i: RecordItem) => item.id === i.id);
      
      if (existingIndex !== -1) {
        list[existingIndex] = item;
      } else {
        list.push(item);
      }
      await FileSystem.writeAsStringAsync(
        DATA_FILE,
        JSON.stringify(list)
      );
    } else {
      await FileSystem.writeAsStringAsync(DATA_FILE, JSON.stringify([item]));
    }
    console.log("数据已保存");
    return item;
  } catch (e) {
    console.error("保存本地记录失败", e);
    Alert.alert("保存本地记录失败");
    return null;
  }
}

async function deleteData(item: RecordItem): Promise<RecordItem[] | null> {
  try {
    const content = await FileSystem.readAsStringAsync(DATA_FILE);
    const list = JSON.parse(content);
    const updatedList = list.filter((i: RecordItem) => i.id !== item.id);
    await FileSystem.writeAsStringAsync(DATA_FILE, JSON.stringify(updatedList));

    //删除本地文件
    if (!item.uri.startsWith('http')){
      const fileInfo = await FileSystem.getInfoAsync(item.uri);
      if (fileInfo.exists) {
        await FileSystem.deleteAsync(item.uri);
      }
    } 

    //删除字幕文件
    const transcriptionDir = FileSystem.documentDirectory + `/${item.id}.json`;
    const transcriptionInfo = await FileSystem.getInfoAsync(transcriptionDir);
    if (transcriptionInfo.exists) {
      await FileSystem.deleteAsync(transcriptionDir);
    }

    console.log("数据已删除");
    return updatedList;
  } catch (e) {
    console.error("删除本地记录失败", e);
    Alert.alert("删除本地记录失败");
    return null;
  }
}

async function updateData(item: RecordItem, updates: Partial<RecordItem>) {
  try {
    const content = await FileSystem.readAsStringAsync(DATA_FILE);
    const list: RecordItem[] = JSON.parse(content);

    const itm = list.find((i) => i.id === item.id);
    if (itm) {
      Object.assign(itm, updates); // 更新所有提供的键
      await FileSystem.writeAsStringAsync(DATA_FILE, JSON.stringify(list));
      return list;
    }

    return null;
  } catch (e) {
    console.error("更新失败", e);
    Alert.alert("更新失败");
    return null;
  }
}


async function getAudioDuration(uri: string) {
  const soundObject = new Audio.Sound();
  try {
    await soundObject.loadAsync({ uri });
    const status = await soundObject.getStatusAsync();
    console.log("status", status);
    if (status.isLoaded) {
      const durationSeconds = status.durationMillis
        ? status.durationMillis / 1000
        : 0;
      await soundObject.unloadAsync();
      return durationSeconds;
    } else {
      return 0;
    }
  } catch (error) {
    console.log("获取音频时长失败", error);
    return 0;
  }
}

async function processFile(
  file: DocumentPicker.DocumentPickerAsset | ImagePicker.ImagePickerAsset,
  id: string
): Promise<RecordItem | null> {
  console.log("已选择文件:", file);
  // 1. 保存到本地
  const originalUri = file.uri;
  const fileName = originalUri.split("/").pop() || "";
  if (!FileSystem.documentDirectory) {
    console.error("FileSystem.documentDirectory is null");
    Alert.alert("此系统不支持上传本地文件");
    return null;
  }
  const destPath = FileSystem.documentDirectory + fileName;
  await FileSystem.copyAsync({ from: originalUri, to: destPath });
  console.log("已保存文件:", destPath);

  // 2. 生成封面
  const mimeType = file.mimeType;
  let coverImage = null;
  if (mimeType?.startsWith("audio")) {
    coverImage = logo;
  } else if (mimeType?.startsWith("video")) {
    try {
      const { uri: thumbnailUri } = await VideoThumbnails.getThumbnailAsync(
        destPath, { time: 0 }
      );
      coverImage = thumbnailUri;
    } catch (e) {
      console.warn("视频缩略图生成失败，使用默认封面", e);
      coverImage = logo;
    }
  } else {
    coverImage = logo; // 兜底封面
  }
  console.log("封面图片:", coverImage);

  // 3. 加载时长
  const duration = await getAudioDuration(destPath);
  console.log("时长:", duration);

  // 4. 新增数据
  const newItem: RecordItem = {
    id,
    type: mimeType?.startsWith("audio") ? "audio" : "video",
    name: fileName,
    duration,
    coverImage,
    date: new Date().toISOString().slice(0, 10),
    uri: destPath,
    currentTime: 0,
    mimeType,
  };
  console.log("新增数据:", newItem);

  // 5. 保存数据
  return await saveData(newItem);
}

async function pickMediaFile() {
  const result = await DocumentPicker.getDocumentAsync({
    type: ["audio/*", "video/*"],
    copyToCacheDirectory: false,
    multiple: false,
  });
  if (!result.canceled) {
    const id = result.assets[0].lastModified?.toString() || Date.now().toString();
    return await processFile(result.assets[0], id);
  } else {
    console.log("已取消选择");
    Alert.alert('已取消选择');
    return null;
  }
}
async function pickVideoFromGallery() {
  const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
  if (!permission.granted) {
    console.log('请授权访问相册');
    Alert.alert('请授权访问相册');
    return null;
  }
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ["videos"],
    allowsMultipleSelection: false,
  });
  if (!result.canceled) {
    const id = result.assets[0].assetId || Date.now().toString();
    return await processFile(result.assets[0], id);
  } else {
    console.log('已取消选择');
    Alert.alert('已取消选择');
    return null;
  }
}

function groupByDate(audioList: RecordItem[]): Section[] {
  const groups: Record<string, RecordItem[]> = {};

  for (const item of audioList) {
    const date = item.date;
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(item);
  }

  // 转换为 SectionList 所需格式
  const sections: Section[] = Object.keys(groups)
    .sort((a, b) => (a > b ? -1 : 1)) // 按日期倒序排列
    .map((date) => ({
      title: date,
      data: groups[date],
    }));

  return sections;
}
function formatDuration(seconds: number) {
  if (seconds <= 0) {
    return "0:00";
  }
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}:${s.toString().padStart(2, "0")}`;
}
const AudioCard = ({ item, onMediaListUpdate }: { item: RecordItem; onMediaListUpdate: (list: RecordItem[]) => void }) => {
  const router = useRouter();
  const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });
  const menuRef = useRef<any>(null);
  //重命名窗口
  const [visible, setVisible] = useState(false);
  const [value, setValue] = useState(item.name);

  const onLongPress = (e: GestureResponderEvent) => {
    const { locationX, locationY } = e.nativeEvent;
    setMenuPosition({ x: locationX, y: locationY });
    menuRef.current?.open();
  };
  const handlePress = () => {
    router.push({
      pathname: "/player",
      params: item,
    });
  };

  const handleDelete = async () => {
    const result = await deleteData(item);
    if (result) {
      onMediaListUpdate(result);
    }
  };

  const handleRename = () => {
    setValue(item.name);
    setVisible(true);
  };

  const onConfirmRename = async () => {
    const result = await updateData(item, { name: value });
    if (result) {
      onMediaListUpdate(result);
      setVisible(false);
    }
  };

  return (
    <View>
      <TouchableOpacity onPress={handlePress} onLongPress={onLongPress}>
        <View
          style={{
            padding: 22,
            marginVertical: 8,
            backgroundColor: "#fff",
            borderRadius: 18,
            flexDirection: "row",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <View style={{ width: "60%", gap: 20 }}>
            <View
              style={{
                backgroundColor: "#e0e0e0",
                borderRadius: 20,
                padding: 8,
                margin: 4,
                alignSelf: "flex-start",
              }}
            >
              <Ionicons name="musical-notes" size={20} color="#333" />
            </View>

            <View>
              <Text style={{ color: "#666", fontSize: 14, fontWeight: "600" }}>
                {formatDuration(item.duration)}
              </Text>
              <Text
                style={{
                  fontSize: 18,
                  fontWeight: "600",
                }}
                numberOfLines={2}
                ellipsizeMode="tail"
              >
                {item.name}
              </Text>
            </View>
          </View>

          <View style={{ padding: 12 }}>
            <Image
              source={
                typeof item.coverImage === "string"
                  ? { uri: item.coverImage }
                  : item.coverImage
              }
              style={{ width: 80, height: 80, borderRadius: 50 }}
              resizeMode="cover"
            />
          </View>
        </View>
      </TouchableOpacity>

      <Menu
        ref={menuRef}
        style={{
          position: "absolute",
          top: menuPosition.y,
          left: menuPosition.x,
        }}
      >
        <MenuTrigger />

        <MenuOptions
          customStyles={{
            optionsContainer: {
              borderRadius: 12,
              width: 100,
              paddingVertical: 10,
            },
          }}
        >
          <MenuOption
            onSelect={handleDelete}
            style={{ margin: 6 }}
            text="删除"
          ></MenuOption>
          <MenuOption
            onSelect={handleRename}
            style={{ margin: 6 }}
            text="重命名"
          ></MenuOption>
        </MenuOptions>
      </Menu>

      {/* 重命名 */}
      <Modal visible={visible} transparent animationType="fade">
        <View
          style={{
            flex: 1,
            backgroundColor: "#00000066",
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <View
            style={{
              backgroundColor: "#fff",
              borderRadius: 12,
              padding: 20,
              width: "80%",
            }}
          >
            <Text style={{ fontSize: 18, marginBottom: 30, fontWeight: "500" }}>
              重命名
            </Text>
            <TextInput
              style={{
                borderWidth: 1,
                borderColor: "#ccc",
                height: 50,
                fontSize: 16,
                borderRadius: 8,
                paddingVertical: 10,
                paddingHorizontal: 20,
                marginBottom: 30,
              }}
              placeholder="新名称"
              value={value}
              onChangeText={setValue}
              autoFocus
            />
            <View
              style={{
                flexDirection: "row",
                justifyContent: "flex-end",
                gap: 10,
              }}
            >
              <TouchableOpacity
                style={{ paddingVertical: 6, paddingHorizontal: 14 }}
                onPress={() => setVisible(false)}
              >
                <Text style={{ color: "#666" }}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={{ paddingVertical: 6, paddingHorizontal: 14 }}
                onPress={onConfirmRename}
              >
                <Text style={{ borderRadius: 6 }}>确定</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
};
const modalOptions: {
  icon: "image" | "camera" | "document";
  label: string;
  description: string;
  onPress: () => Promise<RecordItem | null>;
}[] = [
  {
    icon: "image",
    label: "Blibili 网址",
    description: "在应用中播放 Blibli 视频",
    onPress: () => {
      console.log("Blibili 网址");
      return Promise.resolve(null);
    },
  },
  {
    icon: "image",
    label: "从相册选择",
    description: "选择相册中的图片或视频",
    onPress: pickVideoFromGallery,
  },
  {
    icon: "document",
    label: "从文件选择",
    description: "从文件系统中选择媒体文件",
    onPress: pickMediaFile,
  },
];
export default function AudioListScreen() {
  const [modalVisible, setModalVisible] = useState(false);
  const [mediaList, setMediaList] = useState<Section[]>([]);
  const [refreshing, setRefreshing] = useState(false);

  const router = useRouter();
  const slideAnim = useRef(
    new Animated.Value(Dimensions.get("window").height)
  ).current;

  const openModal = () => {
    setModalVisible(true);
  };

  const closeModal = () => {
    Animated.timing(slideAnim, {
      toValue: Dimensions.get("window").height,
      duration: 300,
      useNativeDriver: true,
    }).start(() => {
      setModalVisible(false);
    });
  };

  // 读取本地数据
  const loadData = async () => {
    try {
      const info = await FileSystem.getInfoAsync(DATA_FILE);
      if (info.exists) {
        const content = await FileSystem.readAsStringAsync(DATA_FILE);
        const grouped = groupByDate(JSON.parse(content));
        setMediaList(grouped);
        await new Promise((resolve) => setTimeout(resolve, 1500));
      }
    } catch (e) {
      console.error("读取本地记录失败", e);
    } finally {
      setRefreshing(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    if (modalVisible) {
      Animated.timing(slideAnim, {
        toValue: 0,
        duration: 300,
        useNativeDriver: true,
      }).start();
    }
  }, [modalVisible, slideAnim]);

  const handleMediaListUpdate = (newList: RecordItem[]) => {
    setMediaList(groupByDate(newList));
  };

  return (
    <MenuProvider>
      <SafeAreaView style={{ flex: 1 }}>
        {/* 标题栏 */}
        <View
          style={{
            flexDirection: "row",
            justifyContent: "space-between",
            alignItems: "center",
            padding: 20,
            borderBottomWidth: 1,
            borderBottomColor: "#e0e0e0",
          }}
        >
          <Text
            style={{
              fontSize: 24,
              fontWeight: "bold",
              color: "#333",
            }}
          >
            SoundBite
          </Text>
          <View style={{ flexDirection: "row", alignItems: "center", gap: 10 }}>
            <TouchableOpacity
              onPress={() => router.push({ pathname: "/search" })}
              style={{
                padding: 8,
              }}
            >
              <Ionicons name="search" size={20} />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={openModal}
              style={{
                backgroundColor: "#e0e0e0",
                padding: 8,
                borderRadius: 50,
              }}
            >
              <Ionicons name="add" size={20} />
            </TouchableOpacity>
          </View>
        </View>

        {/* 列表 */}
        <SectionList
          sections={mediaList}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => (
            <AudioCard item={item} onMediaListUpdate={handleMediaListUpdate} />
          )}
          renderSectionHeader={({ section: { title } }) => (
            <Text
              style={{
                padding: 8,
                fontSize: 16,
                fontWeight: "600",
                color: "#666",
              }}
            >
              {title}
            </Text>
          )}
          contentContainerStyle={{
            padding: 16,
          }}
          stickySectionHeadersEnabled={false}
          refreshing={refreshing}
          onRefresh={loadData}
          ListEmptyComponent={
            <Text
              style={{
                textAlign: "center",
                fontSize: 18,
                marginBottom: 10,
                color: "#666",
              }}
            >
              暂无记录
            </Text>
          }
        />

        {/* 底部弹窗 */}
        <Modal transparent visible={modalVisible} animationType="none">
          <TouchableOpacity
            style={{
              flex: 1,
              backgroundColor: "#00000066",
            }}
            activeOpacity={1}
            onPress={closeModal}
          />
          <Animated.View
            style={{
              position: "absolute",
              left: 0,
              right: 0,
              bottom: 0,
              height: 400,
              backgroundColor: "#fff",
              borderTopLeftRadius: 20,
              borderTopRightRadius: 20,
              padding: 26,
              transform: [{ translateY: slideAnim }],
            }}
          >
            <Text style={{ fontSize: 18, fontWeight: "bold", marginBottom: 6 }}>
              导入视频或音频
            </Text>
            <Text style={{ fontSize: 12, color: "#333", marginBottom: 30 }}>
              请选择从哪里导入媒体文件
            </Text>

            {modalOptions.map((option, index) => (
              <TouchableOpacity
                key={index}
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  paddingHorizontal: 20,
                  paddingVertical: 16,
                  marginVertical: 4,
                  borderRadius: 12,
                  borderWidth: 1,
                  borderColor: "#e0e0e0",
                  backgroundColor: "#f3f3f3ff",
                }}
                onPress={async () => {
                  const item = await option.onPress();
                  if (item) {
                    setMediaList((prev) =>
                      groupByDate([
                        ...prev.flatMap((section) => section.data),
                        item,
                      ])
                    );
                  }
                  closeModal();
                }}
              >
                <Ionicons
                  name={option.icon}
                  size={24}
                  style={{ marginRight: 20 }}
                />
                <View>
                  <Text style={{ fontSize: 15, marginBottom: 6 }}>
                    {option.label}
                  </Text>
                  <Text style={{ fontSize: 12, color: "#333" }}>
                    {option.description}
                  </Text>
                </View>
              </TouchableOpacity>
            ))}
          </Animated.View>
        </Modal>
      </SafeAreaView>
    </MenuProvider>
  );
}
